package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.WebActivity;
import com.jjwxc.jwjskandriod.adapter.CategoryViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.model.ChapterBean;
import com.jjwxc.jwjskandriod.model.SubscribeRequest;
import com.jjwxc.jwjskandriod.model.UserBalanceResponse;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.utils.FileUtils;
import com.jjwxc.jwjskandriod.readActivity.view.TxtChapter;

import java.util.ArrayList;
import java.util.List;

public class DownCharterPop {

    int mBalance = 0;
    PopupWindow mPopWindow;

    public void categoryPopWindow(View mView, Activity context, List<TxtChapter> list, DownChartItemListener itemListener) {

        List<ChapterBean> mList = new ArrayList<>();
        for (TxtChapter chapter : list) {
            if (!chapter.isHasAuth()) {
                ChapterBean bean = new ChapterBean();
                bean.setChapterId(chapter.getChapterId());
                bean.setBookId(chapter.getBookId());
                bean.setHasAuth(chapter.isHasAuth());
                bean.setSelect(false);
                bean.setTitle(chapter.getTitle());
                bean.setVip(chapter.isVip());
                bean.setMonthSubscribe(chapter.isMonthSubscribe());
                bean.setPrice(chapter.getPrice());
                bean.setJuan(chapter.getJuan());
                mList.add(bean);
            }
        }
        View view = LayoutInflater.from(context).inflate(R.layout.downcharter_pop, null, false);

        RecyclerView rv_category = view.findViewById(R.id.rv_category);
        LinearLayout ll_gmxy = view.findViewById(R.id.ll_gmxy);
        TextView tv_buyprice = view.findViewById(R.id.tv_buyprice);
        TextView tv_category = view.findViewById(R.id.tv_category);
        View views = view.findViewById(R.id.view);
        TextView tv_balance = view.findViewById(R.id.tv_balance);
        TextView tv_buy = view.findViewById(R.id.tv_buy);
        ImageView tv_quxiao = view.findViewById(R.id.tv_quxiao);
        TextView tv_allSelect = view.findViewById(R.id.tv_allSelect);
        //设置余额
        getBalance(tv_balance);
        tv_buy.setText("实付0完结币");
        tv_category.setText("完结 共" + list.size() + "章");
        //1.构造一个PopupWindow，参数依次是加载的 View，宽高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //设置加载动画
        popWindow.setAnimationStyle(R.style.PopupWindow);
        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1, context);
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效
        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0);

        mPopWindow = popWindow;
        setBackgroundAlpha(0.3f, context);

        rv_category.setNestedScrollingEnabled(false);
        rv_category.setFocusable(false);
        rv_category.setLayoutManager(new LinearLayoutManager(context));
        rv_category.addItemDecoration(new LinearLayouDecoration(context,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        rv_category.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题

        CategoryAdapter categoryAdapter = new CategoryAdapter(context, tv_buy);
        rv_category.setAdapter(categoryAdapter);
        categoryAdapter.setData(mList);
        ll_gmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(context, WebActivity.class);
                intent.putExtra("WEB_URL", Url.help4);
                intent.putExtra("WEB_NAME", "购买须知");
                context.startActivity(intent);
            }
        });

        tv_buyprice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (price > mBalance) {
                    new BuyWjbPop().buyWjbWindow(mView, context, price + "", value -> {
                        //更新余额
                        getBalance(tv_balance);
                    });
                    return;
                }
                List<TxtChapter> slist = new ArrayList<>();
                List<String> ids = new ArrayList<>();
                for (int i = 0; i < mListone.size(); i++) {
                    TxtChapter txtChapter = new TxtChapter();
                    txtChapter.setChapterId(mListone.get(i).getChapterId());
                    txtChapter.setBookId(mListone.get(i).getBookId());
                    txtChapter.setTitle(mListone.get(i).getTitle());
                    txtChapter.setHasAuth(mListone.get(i).isHasAuth());
                    slist.add(txtChapter);
                    ids.add(mListone.get(i).getChapterId());
                }
                if (slist.size() > 0) {
                    SubscribeRequest request = new SubscribeRequest();
                    request.setBookId(slist.get(0).getBookId());
                    request.setSubscribeType("batch");
                    request.setChapterIds(ids);
                    new FFNetWork().post(Url.subscribe, null, new FFNetWorkCallBack<String>() {
                        @SuppressLint("CheckResult")
                        @Override
                        public void onSuccess(String response) {
                            if (response.contains("200")) {
                                for (int i = 0; i < slist.size(); i++) {
                                    //删除未购买已经缓存的空章节
                                    FileUtils.chapterCachedDelete(slist.get(i).getBookId(), slist.get(i).getChapterId());
                                }
                                itemListener.onItemClick(1);
                                ((ReadActivity) context).mPresenter.loadChapter(slist.get(0).getBookId(), slist);
                                FFApplication.showToast("成功购买并开始下载" + slist.size() + "章节");
                                //更新余额
                                getBalance(tv_balance);
                                popWindow.dismiss();
                            }

                        }

                        @Override
                        public boolean onFail(String response) {
                            return false;
                        }
                    }, String.class, JSON.toJSONString(request));
                }
            }
        });

        tv_allSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                price = 0;
                mListone.clear();
                for (ChapterBean bean : mList) {
                    bean.setSelect(true);
                    if (!bean.isHasAuth()) {
                        price = price + Integer.parseInt(bean.getPrice());
                    }
                    mListone.add(bean);
                }
                categoryAdapter.notifyDataSetChanged();
                tv_buy.setText("实付" + price + "完结币");
            }
        });
        tv_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemListener.onItemClick(-1);
                popWindow.dismiss();

            }
        });
        views.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemListener.onItemClick(-1);
                popWindow.dismiss();
            }
        });
    }

    List<ChapterBean> mListone = new ArrayList<>();
    int price;

    public class CategoryAdapter extends BaseRecyclerAdapter<CategoryViewHolder> {
        private Context context;
        private TextView tv_buy;


        private List<ChapterBean> mData = new ArrayList<>();


        public CategoryAdapter(Context cnt, TextView tv_buy) {
            this.context = cnt;
            this.tv_buy = tv_buy;

        }

        public void addData(List<ChapterBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<ChapterBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.downcharter_pop_item, parent, false);
            CategoryViewHolder viewHolder_text = new CategoryViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public CategoryViewHolder getViewHolder(View view) {
            return new CategoryViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final CategoryViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            holder.tv_name.setText(mData.get(position).getTitle());
            holder.tv_price.setText(mData.get(position).getPrice() + "完结币");
            if (mData.get(position).isSelect()) {
                holder.img_down.setImageResource(R.mipmap.check_box_two);
            } else {
                holder.img_down.setImageResource(R.mipmap.check_box_one);
            }
            holder.cl_down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.get(position).isSelect()) {
                        if (!mData.get(position).isHasAuth()) {
                            price = price - Integer.parseInt(mData.get(position).getPrice());
                        }
                        mData.get(position).setSelect(false);
                        holder.img_down.setImageResource(R.mipmap.check_box_one);
                        mListone.remove(mData.get(position));
                    } else {
                        if (!mData.get(position).isHasAuth()) {
                            price = price + Integer.parseInt(mData.get(position).getPrice());
                        }
                        mListone.add(mData.get(position));
                        mData.get(position).setSelect(true);
                        holder.img_down.setImageResource(R.mipmap.check_box_two);
                    }
                    tv_buy.setText("实付" + price + "完结币");
                }
            });

        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }

    public void getBalance(TextView textView) {
        new FFNetWork().post(Url.balance, null, new FFNetWorkCallBack<UserBalanceResponse>() {
            @Override
            public void onSuccess(UserBalanceResponse response) {
                if (response.getCode() == 200) {
                    mBalance = response.getData().getBalance();
                    textView.setText("余额" + mBalance + "完结币");
                }

            }

            @Override
            public boolean onFail(UserBalanceResponse response) {
                return false;
            }
        }, UserBalanceResponse.class);
    }

    public interface DownChartItemListener {
        //-1 不刷新，0刷新，1刷新目录
        void onItemClick(int refresh);
    }

    public void setBackgroundAlpha(float alpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = alpha;
        activity.getWindow().setAttributes(lp);
    }
}
